<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Exploring Design Patterns in Rust with Algorithmic Trading Examples - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html" class="active"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="exploring-design-patterns-in-rust-with-algorithmic-trading-examples"><a class="header" href="#exploring-design-patterns-in-rust-with-algorithmic-trading-examples">Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></h1>
<p>作者：<a href="https://siddharthqs.com/?source=top_nav_blog_home">Siddharth</a></p>
<p>原文：<a href="https://siddharthqs.com/design-patterns-in-rust">https://siddharthqs.com/design-patterns-in-rust</a></p>
<h1 id="the-solid-design-principles"><a class="header" href="#the-solid-design-principles">The SOLID Design Principles</a></h1>
<p>Let's review the SOLID design principles since we'll mention them while discussing design patterns. It's helpful to remember these principles when designing maintainable and scalable object-oriented systems.</p>
<ol>
<li>Single Responsibility Principle (SRP): A class should have only one reason to exist, meaning it should have only one job or responsibility. You should not overload your objects with two many responsibility, just create a new class for it.</li>
<li>Open/Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means you should be able to add new functionality without changing existing code.</li>
<li>Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This ensures that a subclass can stand in for its superclass.</li>
<li>Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use. This means creating smaller, more specific interfaces rather than a large, general-purpose one.</li>
<li>Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details. Details should depend on abstractions. This principle helps in reducing the coupling between different parts of a system.</li>
</ol>
<h1 id="strategy-pattern"><a class="header" href="#strategy-pattern">Strategy pattern</a></h1>
<p>The Strategy design pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. This pattern is based on composition. Lets see the definition from the “<a href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets algorithm vary independently from clients that use it.</p>
</blockquote>
<p>It is naturally useful in trading systems where algorithms need to switch between different execution methods. In this example, we'll implement a simplified trading system in Rust that executes orders using different strategies like TWAP (Time-Weighted Average Price), VWAP (Volume-Weighted Average Price), and POV (Percentage of Volume). These are your execution strategies. You can choose one of the strategies based on certain factors or constraints.</p>
<h2 id="structure"><a class="header" href="#structure">Structure</a></h2>
<ol>
<li>The <strong>Strategy</strong> interface is common to all concrete strategies. It declares a method the context uses to execute a strategy. We define a common interface for all execution strategies, the method <code>execute_order</code> that all execution strategies must implement.</li>
</ol>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>trait ExecutionStrategy {
    fn execute_order(&amp;self, order_id: u32, quantity: u32);
}
<span class="boring">}
</span></code></pre></pre>
<ol>
<li>
<p><strong>Concrete Strategies</strong> implement different variations of an algorithm the context uses. In this example, we write implementations of TWAP, VWAP, and POV strategies.</p>
<p>Copy</p>
<p>Copy</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span> struct TwapStrategy;

 impl ExecutionStrategy for TwapStrategy {
     fn execute_order(&amp;self, order_id: u32, quantity: u32) {
         println!(&quot;Executing order {} using TWAP for {} units.&quot;, order_id, quantity);
         // Implement TWAP logic here
     }
 }
 struct VwapStrategy;

 impl ExecutionStrategy for VwapStrategy {
     fn execute_order(&amp;self, order_id: u32, quantity: u32) {
         println!(&quot;Executing order {} using VWAP for {} units.&quot;, order_id, quantity);
         // Implement VWAP logic here
     }
 }
 struct PovStrategy {
     participation_rate: f64,
 }

 impl ExecutionStrategy for PovStrategy {
     fn execute_order(&amp;self, order_id: u32, quantity: u32) {
         println!(
             &quot;Executing order {} using POV at {}% participation for {} units.&quot;,
             order_id, self.participation_rate * 100.0, quantity
         );
         // Implement POV logic here
     }
 }
<span class="boring">}
</span></code></pre></pre>
</li>
<li>
<p>The <strong>Context</strong> maintains a reference to one of the concrete strategies and communicates with this object only via the strategy interface. Here we write the <code>OrderExecutor</code> that holds a reference to a strategy and uses it to execute orders. The context calls the execution method on the linked strategy object each time it needs to run the algorithm. The context doesn’t know what type of strategy it works with or how the algorithm is executed.</p>
<p>Copy</p>
<p>Copy</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span> struct OrderExecutor {
     strategy: Box&lt;dyn ExecutionStrategy&gt;,
 }

 impl OrderExecutor {
     fn new(strategy: Box&lt;dyn ExecutionStrategy&gt;) -&gt; Self {
         OrderExecutor { strategy }
     }
     fn set_strategy(&amp;mut self, strategy: Box&lt;dyn ExecutionStrategy&gt;) {
         self.strategy = strategy;
     }
     fn execute(&amp;self, order_id: u32, quantity: u32) {
         self.strategy.execute_order(order_id, quantity);
     }
 }
<span class="boring">}
</span></code></pre></pre>
</li>
<li>
<p>The <strong>Client</strong> creates a specific strategy object and passes it to the context. The context exposes a setter which lets clients replace the strategy associated with the context at runtime.</p>
<pre><pre class="playground"><code class="language-rust"> fn main() {
     let order_id = 101;
     let quantity = 1000;

     // Using TWAP Strategy
     let twap_strategy = Box::new(TwapStrategy);
     let mut executor = OrderExecutor::new(twap_strategy);
     executor.execute(order_id, quantity);

     // Switching to VWAP Strategy
     let vwap_strategy = Box::new(VwapStrategy);
     executor.set_strategy(vwap_strategy);
     executor.execute(order_id+1, quantity);

     // Switching to POV Strategy
     let pov_strategy = Box::new(PovStrategy {
         participation_rate: 0.1,
     });
     executor.set_strategy(pov_strategy);
     executor.execute(order_id+2, quantity);
 }
</code></pre></pre>
</li>
</ol>
<p><img src="assets/0010.avif" alt="" /></p>
<h3 id="strategy-pattern-class-diagram"><a class="header" href="#strategy-pattern-class-diagram">Strategy pattern Class Diagram</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>+-----------------------------------------------------------------+
| &lt;&lt;interface&gt;&gt;                                                   |
| ExecutionStrategy                                               |
|-----------------------------------------------------------------|
| + execute_order(...)                                            |
+-----------------------------------------------------------------+

     /|\                  /|\                   /|\
      |                    |                     |
      |                    |                     |
+---------------+     +--------------+       +--------------+
| TwapStrategy  |     | VwapStrategy |       | PovStrategy  |
|---------------|     |--------------|       |--------------|
|               |     |              |       | - participation_rate: f64 |
|---------------|     |--------------|       |--------------|
| + execute_order(...)|+ execute_order(...)  |+ execute_order(...)|
+---------------+     +--------------+       +--------------+

+-----------------------------+
| OrderExecutor               |
|-----------------------------|
| - strategy: ExecutionStrategy |
|-----------------------------|
| + new(strategy)             |
| + set_strategy(strategy)    |
| + execute(order_id, quantity) |
+-----------------------------+
<span class="boring">}
</span></code></pre></pre>
<h1 id="observer-design-pattern"><a class="header" href="#observer-design-pattern">Observer Design Pattern</a></h1>
<p>The <strong>Observer</strong> design pattern is a behavioral design pattern that enables an object, known as the <strong>Subject</strong>, to maintain a list of its dependents, called <strong>Observers</strong>, and automatically notify them of any state changes, typically by calling one of their methods. This pattern is particularly useful in <strong>Event-Driven Systems</strong>, when you need to notify multiple objects about events without tightly coupling them. The definition from the “<a href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The observer pattern defines a one to many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.</p>
</blockquote>
<p>In the context of algorithmic trading , the Observer pattern can be applied to scenarios such as:</p>
<ul>
<li><strong>Market Data Feeds</strong>: Notifying trading strategies when new market data arrives.</li>
<li><strong>Order Execution Updates</strong>: Informing interested parties when an order is executed or its status changes.</li>
<li><strong>Price Alerts</strong>: Triggering alerts when certain price thresholds are crossed.</li>
</ul>
<h2 id="structure-1"><a class="header" href="#structure-1">Structure</a></h2>
<ul>
<li><strong>Subject (Observable or Publisher)</strong>: The Subject issues events of interest to other objects. These events occur when the subject (publisher) changes its state or executes some behaviors. Subjects maintain a subscription infrastructure, list of observers and provides methods to attach, detach, and notify them.</li>
<li><strong>Observer (Subscriber)</strong>: The <strong>Observer</strong> interface declares the notification interface. In most cases, it consists of a single <code>update</code> method.</li>
<li><strong>Concrete Subject</strong>: Implements the subject interface and holds the state of interest.</li>
<li><strong>Concrete Observer</strong>: <strong>Concrete Observer</strong> perform some actions in response to notifications issued by the subject. All of these classes must implement the same interface so the subject isn’t coupled to concrete classes.</li>
</ul>
<p>Usually, subscribers need some contextual information to handle the update correctly. For this reason, publishers often pass some context data as arguments of the notification method. The publisher can pass itself as an argument, letting subscriber fetch any required data directly.</p>
<h2 id="implementation-example"><a class="header" href="#implementation-example">Implementation Example</a></h2>
<p>We will implement a simplified version of trading system using Rust where we have:</p>
<ul>
<li><strong>Market Data Feed</strong> (Subject): Provides live price updates for various financial instruments.</li>
<li><strong>Trading Strategies</strong> (Observers): React to market data updates to make trading decisions.</li>
</ul>
<p>Let look at the code implementation.</p>
<h3 id="observer-trait"><a class="header" href="#observer-trait">Observer Trait</a></h3>
<p>The <code>Observer</code> trait declares the <code>update</code> method, which observers must implement.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::rc::Rc;
use std::cell::RefCell;

trait Observer {
    fn update(&amp;self, instrument_id: &amp;str, price: f64);
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="implement-concrete-observers-trading-strategies"><a class="header" href="#implement-concrete-observers-trading-strategies">Implement Concrete Observers (Trading Strategies)</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct MomentumStrategy {
    name: String,
    threshold: f64,
}

impl Observer for MomentumStrategy {
    fn update(&amp;self, instrument_id: &amp;str, price: f64) {
        if price &gt; self.threshold {
            println!(
                &quot;{}: [{}] Price crossed above threshold! Price: {}&quot;,
                self.name, instrument_id, price
            );
            // Implement buy logic
        } else {
            println!(
                &quot;{}: [{}] Price below threshold. Price: {}&quot;,
                self.name, instrument_id, price
            );
            // Implement hold or sell logic
        }
    }
}

struct MeanReversionStrategy {
    name: String,
    average_price: RefCell&lt;f64&gt;,
}

impl Observer for MeanReversionStrategy {
    fn update(&amp;self, instrument_id: &amp;str, price: f64) {
        let mut avg = self.average_price.borrow_mut();
        *avg = (*avg * 0.9) + (price * 0.1); // Update moving average
        if price &lt; *avg {
            println!(
                &quot;{}: [{}] Price below average! Price: {}, Average: {:.2}&quot;,
                self.name, instrument_id, price, *avg
            );
            // Implement buy logic
        } else {
            println!(
                &quot;{}: [{}] Price above average. Price: {}, Average: {:.2}&quot;,
                self.name, instrument_id, price, *avg
            );
            // Implement sell logic
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="define-the-subject-trait"><a class="header" href="#define-the-subject-trait">Define the Subject Trait</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>trait Subject {
    fn attach(&amp;mut self, observer: Rc&lt;dyn Observer&gt;);
    fn detach(&amp;mut self, observer: &amp;Rc&lt;dyn Observer&gt;);
    fn notify(&amp;self);
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="implement-the-concrete-subject-market-data-feed"><a class="header" href="#implement-the-concrete-subject-market-data-feed">Implement the Concrete Subject (Market Data Feed)</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct MarketDataFeed {
    instrument_id: String,
    observers: RefCell&lt;Vec&lt;Rc&lt;dyn Observer&gt;&gt;&gt;,
    price: RefCell&lt;f64&gt;,
}

impl MarketDataFeed {
    fn new(instrument_id: &amp;str) -&gt; Self {
        MarketDataFeed {
            instrument_id: instrument_id.to_string(),
            observers: RefCell::new(Vec::new()),
            price: RefCell::new(0.0),
        }
    }
    fn set_price(&amp;self, new_price: f64) {
        *self.price.borrow_mut() = new_price;
        self.notify();
    }
}
impl Subject for MarketDataFeed {
    fn attach(&amp;mut self, observer: Rc&lt;dyn Observer&gt;) {
        self.observers.borrow_mut().push(observer);
    }
    fn detach(&amp;mut self, observer: &amp;Rc&lt;dyn Observer&gt;) {
        let mut observers = self.observers.borrow_mut();
        if let Some(pos) = observers.iter().position(|x| Rc::ptr_eq(x, observer)) {
            observers.remove(pos);
        }
    }
    fn notify(&amp;self) {
        let price = *self.price.borrow();
        let instrument_id = &amp;self.instrument_id;
        for observer in self.observers.borrow().iter() {
            observer.update(instrument_id, price);
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="client-code"><a class="header" href="#client-code">Client Code</a></h3>
<pre><pre class="playground"><code class="language-rust">fn main() {
    // Create market data feed for AAPL
    let mut market_data_feed = MarketDataFeed::new(&quot;AAPL&quot;);

    // Create observers
    let momentum_strategy: Rc&lt;dyn Observer&gt; = Rc::new(MomentumStrategy {
        name: String::from(&quot;MomentumStrategy&quot;),
        threshold: 150.0,
    });

    let mean_reversion_strategy: Rc&lt;dyn Observer&gt; = Rc::new(MeanReversionStrategy {
        name: String::from(&quot;MeanReversionStrategy&quot;),
        average_price: RefCell::new(145.0),
    });

    // Attach observers
    market_data_feed.attach(momentum_strategy.clone());
    market_data_feed.attach(mean_reversion_strategy.clone());

    // Simulate market data updates
    let price_updates = vec![148.0, 151.0, 149.5, 152.5, 147.0];

    for price in price_updates {
        println!(&quot;\nMarketDataFeed [{}]: New price is {}&quot;, &quot;AAPL&quot;, price);
        market_data_feed.set_price(price);
    }

    // Detach momentum strategy
    market_data_feed.detach(&amp;momentum_strategy);

    // More updates
    let more_price_updates = vec![153.0, 146.5];

    for price in more_price_updates {
        println!(&quot;\nMarketDataFeed [{}]: New price is {}&quot;, &quot;AAPL&quot;, price);
        market_data_feed.set_price(price);
    }
}
</code></pre></pre>
<p><img src="assets/0020.avif" alt="" /></p>
<h3 id="notes-on-rust-implementation"><a class="header" href="#notes-on-rust-implementation">Notes on Rust Implementation</a></h3>
<ul>
<li><strong>Reference Counting (</strong><code>Rc</code>): Used to allow multiple ownership of observers by the subject.</li>
<li><strong>Interior Mutability (</strong><code>RefCell</code>): Allows us to mutate data even when it is wrapped in an immutable reference, which is necessary when observers need to update their internal state upon receiving updates.</li>
<li><strong>Trait Objects (</strong><code>dyn Trait</code>): Trait objects like <code>dyn Observer</code> allow for dynamic dispatch in Rust. They allow the subject to hold a collection of different types that implement the same trait.</li>
</ul>
<p>In Rust, comparing trait objects (<code>dyn Observer</code>) directly is not straightforward because trait objects do not implement <code>PartialEq</code> by default. We use <code>Rc::ptr_eq</code> to compare the pointers of the <code>Rc</code> smart pointers, which checks if they point to the same allocation.</p>
<p>In the line, if we don’t explicitly say the type Rc<dyn Observer> then momentum_strategy will be of type Rc<MomentumStrategy> and it will be fine for attach method however not work with detach method.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let momentum_strategy: Rc&lt;dyn Observer&gt; = Rc::new(MomentumStrategy{...});
<span class="boring">}
</span></code></pre></pre>
<p>In Rust, even though <code>MomentumStrategy</code> implements the <code>Observer</code> trait, <code>Rc&lt;MomentumStrategy&gt;</code> and <code>Rc&lt;dyn Observer&gt;</code> are different types and are not directly interchangeable.</p>
<p>Note: The <code>Rc::ptr_eq</code> function requires that both <code>Rc</code> pointers have the same type parameter. By ensuring that both <code>Rc</code> pointers are of type <code>Rc&lt;dyn Observer&gt;</code>, we satisfy this requirement.</p>
<p>Rust can automatically coerce a reference to a concrete type into a reference to a trait object if the type implements the trait. This is what happens when you assign <code>Rc::new(MomentumStrategy { /* fields */ })</code> to a variable of type <code>Rc&lt;dyn Observer&gt;</code>.</p>
<h1 id="decorator-pattern"><a class="header" href="#decorator-pattern">Decorator Pattern</a></h1>
<p>The <strong>Decorator Pattern</strong> is a structural design pattern that allows behavior to be added to individual objects dynamically without affecting the behavior of other objects from the same class. The definition from the “<a href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provides a flexible alternative to subclassing for extending functionality.</p>
</blockquote>
<h2 id="structure-2"><a class="header" href="#structure-2">Structure</a></h2>
<ul>
<li><strong>Component Interface</strong>: Defines the interface for objects that can have responsibilities added to them dynamically.</li>
<li><strong>Concrete Component</strong>: The original object to which additional responsibilities are added.</li>
<li><strong>Decorator</strong>: Abstract class that implements the component interface and contains a reference to a component object.</li>
<li><strong>Concrete Decorators</strong>: Extend the functionality of the component by overriding methods and adding additional behaviors.</li>
</ul>
<h3 id="uml-diagram"><a class="header" href="#uml-diagram">UML Diagram</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>+------------------+
|    Component     |&lt;---------------------------+
+------------------+                            |
| + operation()    |                            |
+------------------+                            |
          ^                                     |
          |                                     |
+------------------+          +------------------+
| ConcreteComponent|          |    Decorator     |
+------------------+          +------------------+
| + operation()    |          | - component      |
+------------------+          | + operation()    |
                              +------------------+
                                       ^
                                       |
                      +----------------+----------------+
                      |                                 |
            +------------------+               +------------------+
            | ConcreteDecoratorA|               | ConcreteDecoratorB|
            +------------------+               +------------------+
            | + operation()    |               | + operation()    |
            +------------------+               +------------------+
<span class="boring">}
</span></code></pre></pre>
<h2 id="example-enhancing-order-execution-with-decorators"><a class="header" href="#example-enhancing-order-execution-with-decorators">Example: Enhancing Order Execution with Decorators</a></h2>
<p>We have an <code>OrderExecutor</code> component responsible for executing trades. We want to add additional behaviors:</p>
<ul>
<li><strong>LoggingDecorator</strong>: Logs the details of each order execution.</li>
<li><strong>ValidationDecorator</strong>: Validates orders before execution.</li>
</ul>
<h3 id="component-trait"><a class="header" href="#component-trait">Component Trait</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[derive(Debug)]
struct Order {
    symbol: String,
    quantity: i32,
    price: f64,
}
trait OrderExecutor {
    fn execute_order(&amp;self, order: &amp;Order) -&gt; Result&lt;(), String&gt;;
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="concrete-component"><a class="header" href="#concrete-component">Concrete Component</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct BasicOrderExecutor;

impl OrderExecutor for BasicOrderExecutor {
    fn execute_order(&amp;self, order: &amp;Order) -&gt; Result&lt;(), String&gt; {
        // Simulate order execution logic
        println!(&quot;Executing order: {:?}&quot;, order);
        Ok(())
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="concrete-decorators"><a class="header" href="#concrete-decorators">Concrete Decorators</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct LoggingDecorator&lt;T: OrderExecutor&gt; {
    executor: T,
}

impl&lt;T: OrderExecutor&gt; LoggingDecorator&lt;T&gt; {
    fn new(executor: T) -&gt; Self {
        LoggingDecorator { executor }
    }
}

impl&lt;T: OrderExecutor&gt; OrderExecutor for LoggingDecorator&lt;T&gt; {
    fn execute_order(&amp;self, order: &amp;Order) -&gt; Result&lt;(), String&gt; {
        println!(&quot;LoggingDecorator: Order received: {:?}&quot;, order);
        let result = self.executor.execute_order(order);
        println!(&quot;LoggingDecorator: Order execution result: {:?}&quot;, result);
        result
    }
}
struct ValidationDecorator&lt;T: OrderExecutor&gt; {
    executor: T,
}

impl&lt;T: OrderExecutor&gt; ValidationDecorator&lt;T&gt; {
    fn new(executor: T) -&gt; Self {
        ValidationDecorator { executor }
    }
}

impl&lt;T: OrderExecutor&gt; OrderExecutor for ValidationDecorator&lt;T&gt; {
    fn execute_order(&amp;self, order: &amp;Order) -&gt; Result&lt;(), String&gt; {
        if self.validate(order) {
            println!(&quot;Validated Order: {:?}&quot;, order);
            self.executor.execute_order(order)
        } else {
            Err(String::from(&quot;Validation failed&quot;))
        }
    }
}

impl&lt;T: OrderExecutor&gt; ValidationDecorator&lt;T&gt; {
    fn validate(&amp;self, order: &amp;Order) -&gt; bool {
        // Implement validation logic
        order.quantity &gt; 0 &amp;&amp; order.price &gt; 0.0
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="client-code-1"><a class="header" href="#client-code-1">Client Code</a></h3>
<pre><pre class="playground"><code class="language-rust">fn main() {
    let order = Order {
        symbol: String::from(&quot;AAPL&quot;),
        quantity: 100,
        price: 150.0,
    };

    // Basic executor
    let basic_executor = BasicOrderExecutor;

    // Decorate with validation
    let validated_executor = ValidationDecorator::new(basic_executor);

    // Further decorate with logging
    let logged_executor = LoggingDecorator::new(validated_executor);

    // Execute the order
    let result = logged_executor.execute_order(&amp;order);
    match result {
        Ok(_) =&gt; println!(&quot;Order executed successfully.&quot;),
        Err(e) =&gt; println!(&quot;Order execution failed: {}&quot;, e),
    }
}
</code></pre></pre>
<p><img src="assets/0030.avif" alt="" /></p>
<h3 id="notes-on-rust-implementation-1"><a class="header" href="#notes-on-rust-implementation-1">Notes on Rust Implementation</a></h3>
<p>In this example, I used generics allowing static dispatch. By the way, in Rust, <strong>traits</strong> are not types themselves; they are a collection of methods that types can implement. You cannot instantiate a trait directly or store it as a field without using a pointer or a generic parameter. The following will result in compilation error because OrderExecutor is a trait.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct ValidationDecorator {
    executor: OrderExecutor,
}
<span class="boring">}
</span></code></pre></pre>
<p>In Rust, all types must have a known size at compile time unless they are behind a pointer (like <code>&amp;</code>, <code>Box</code>, or <code>Rc</code>) or used as a generic type parameter with trait bounds. By default, all generic type parameters and struct fields have an implicit <code>Sized</code> bound. This means that the compiler needs to know the size of the type at compile time.</p>
<p>The choice between generics and trait objects depends on your specific needs for performance and flexibility.</p>
<p>Instead of generics, you can use Trait Objects as follows:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct ValidationDecorator {
    executor: Box&lt;dyn OrderExecutor&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p>This uses <strong>dynamic dispatch</strong>, which introduces a slight runtime overhead due to the use of a vtable.</p>
<h1 id="factory-method-pattern"><a class="header" href="#factory-method-pattern">Factory Method Pattern</a></h1>
<p><strong>Factory Method</strong> is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This definition is by the <a href="https://refactoring.guru/design-patterns/factory-method">refactoring.guru</a>. The “<a href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>” more or less says the same:</p>
<blockquote>
<p>The Factory Method Patterns defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p>
</blockquote>
<h2 id="structure-3"><a class="header" href="#structure-3">Structure</a></h2>
<ul>
<li><strong>Product Interface</strong>: Defines the interface of objects the factory method creates.</li>
<li><strong>Concrete Products</strong>: Various implementations of the product interface.</li>
<li><strong>Creator (Factory)</strong>: Declares the factory method that returns new product objects.</li>
<li><strong>Concrete Creators</strong>: Override the factory method to change the resulting product's type.</li>
</ul>
<h3 id="uml-diagram-1"><a class="header" href="#uml-diagram-1">UML Diagram</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>+------------------+
|    Creator       |&lt;---------------------------+
+------------------+                            |
| + factoryMethod()|                            |
+------------------+                            |
            ^                                   |
            |                                   |
+------------------+          +------------------+
| ConcreteCreator  |          |   Product        |
+------------------+          +------------------+
| + factoryMethod()|          | + operation()    |
+------------------+          +------------------+
                                         ^
                                         |
                          +---------------------------+
                          |                           |
                +------------------+        +------------------+
                | ConcreteProductA |        | ConcreteProductB |
                +------------------+        +------------------+
                | + operation()    |        | + operation()    |
                +------------------+        +------------------+
<span class="boring">}
</span></code></pre></pre>
<h2 id="example-order-creation-factory"><a class="header" href="#example-order-creation-factory">Example: Order Creation Factory</a></h2>
<p>Let's consider an example where we need to create different types of orders based on the current state of our trading strategy.</p>
<h3 id="order-types"><a class="header" href="#order-types">Order Types</a></h3>
<ul>
<li><strong>Market Order</strong>: Executes immediately at the current market price.</li>
<li><strong>Limit Order</strong>: Executes at a specified price or better.</li>
<li><strong>Stop Order</strong>: Becomes a market order when a specified price is reached.</li>
</ul>
<h3 id="product-interface"><a class="header" href="#product-interface">Product Interface</a></h3>
<p>This interface is common to all the objects (in our case order types) that can be produced by the creator and its subclasses.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>trait Order {
    fn place(&amp;self);
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="concrete-products"><a class="header" href="#concrete-products">Concrete Products</a></h3>
<p><strong>Concrete Products</strong> are different implementations of the product interface. In our case different implementation of order types.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct MarketOrder {
    symbol: String,
    quantity: u32,
}

impl Order for MarketOrder {
    fn place(&amp;self) {
        println!(&quot;Placing Market Order: Buy {} units of {} at market price.&quot;,
            self.quantity, self.symbol
        );
        // Implement order placement logic here
    }
}
struct LimitOrder {
    symbol: String,
    quantity: u32,
    limit_price: f64,
}

impl Order for LimitOrder {
    fn place(&amp;self) {
        println!(&quot;Placing Limit Order: Buy {} units of {} at ${}.&quot;,
            self.quantity, self.symbol, self.limit_price
        );
        // Implement order placement logic here
    }
}
struct StopOrder {
    symbol: String,
    quantity: u32,
    stop_price: f64,
}

impl Order for StopOrder {
    fn place(&amp;self) {
        println!(
            &quot;Placing Stop Order: Buy {} units of {} when price reaches ${}.&quot;,
            self.quantity, self.symbol, self.stop_price
        );
        // Implement order placement logic here
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="creator-order-factory"><a class="header" href="#creator-order-factory">Creator (Order Factory)</a></h3>
<p>It returns a different type of order.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum OrderType {
    Market,
    Limit(f64), // Limit price
    Stop(f64),  // Stop price
}
struct OrderFactory;

impl OrderFactory {
    fn create_order(order_type: OrderType, symbol: String, quantity: u32) -&gt; Box&lt;dyn Order&gt; {
        match order_type {
            OrderType::Market =&gt; Box::new(MarketOrder { symbol, quantity }),
            OrderType::Limit(limit_price) =&gt; Box::new(LimitOrder {
                symbol,
                quantity,
                limit_price,
            }),
            OrderType::Stop(stop_price) =&gt; Box::new(StopOrder {
                symbol,
                quantity,
                stop_price,
            }),
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="client-code-2"><a class="header" href="#client-code-2">Client Code</a></h3>
<pre><pre class="playground"><code class="language-rust">fn main() {
    let symbol = String::from(&quot;AAPL&quot;);
    let quantity = 100;
    // Decide which order type to use
    let order_type = OrderType::Limit(149.0);
    // Create the order using the factory
    let order = OrderFactory::create_order(order_type, symbol.clone(), quantity);
    // Place the order
    order.place();
}
</code></pre></pre>
<p><img src="assets/0040.avif" alt="" /></p>
<h1 id="singleton"><a class="header" href="#singleton"><strong>Singleton</strong></a></h1>
<p><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance. Overall Singleton has almost the same pros and cons as global variables.</p>
<p>In <strong>Rust</strong>, implementing singletons are pretty tricky due to its ownership model and emphasis on safe concurrency. It must solve these two problem:</p>
<ul>
<li><strong>Ensure a Class Has Only One Instance</strong>: Prevents multiple instances, guaranteeing that all clients use the same instance.</li>
<li><strong>Provide a Global Point of Access</strong>: Offers a way to access the single instance from anywhere in the application.</li>
</ul>
<p>Rust discourages global mutable state to prevent data races and ensure thread safety. And any global state must be safe to access from multiple threads. All these makes implementing singletons non-trivial. We can achieve this using different approach like using Mutex, static lifetime, OnceCell crate.</p>
<p>While a mutable singleton can be convenient, global mutable state can lead to code that's difficult to maintain and test. You always have option to pass the instance as a parameter to the parts of your code that need it. As we are discussing singletons, lets see the implementation using OnceCell.</p>
<h2 id="oncecell"><a class="header" href="#oncecell"><a href="https://crates.io/crates/once_cell">OnceCell</a></a></h2>
<p>When you need to initialize data at runtime, possibly in a lazy manner, and ensure it is set only once. The core API looks <em>roughly</em> like</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl OnceCell&lt;T&gt; {
    fn new() -&gt; OnceCell&lt;T&gt; { ... }
    fn set(&amp;self, value: T) -&gt; Result&lt;(), T&gt; { ... }
    fn get(&amp;self) -&gt; Option&lt;&amp;T&gt; { ... }
}
<span class="boring">}
</span></code></pre></pre>
<p>OnceCell has two varient <code>std::cell::OnceCell&lt;T&gt;</code> for single-threaded scenarios and <code>std::sync::OnceCell&lt;T&gt;</code> for thread-safe scenarios, can be shared between threads.</p>
<p>https://github.com/matklad/once_cell</p>
<p>However, since <code>OnceCell</code> provides immutable access to the initialized value, we need a way to mutate the instance after it's been set because singleton patterns allows mutable instance. To achieve a mutable singleton, we need combine <code>OnceCell</code> with interior mutability patterns. This involves wrapping the struct in types that allow mutation through immutable references, such as <code>RefCell</code> for single-threaded applications or <code>Mutex</code>/<code>RwLock</code> for multi-threaded applications.</p>
<h2 id="example-trading-system-configmanager"><a class="header" href="#example-trading-system-configmanager">Example: Trading System ConfigManager</a></h2>
<h3 id="config"><a class="header" href="#config">Config</a></h3>
<p>The <code>Config</code> struct holds various configuration settings. It derives <code>Deserialize</code> to allow loading from a JSON file.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Config {
    pub api_key: String,
    pub db_connection_string: String,
    pub trading_parameters: TradingParameters,
}

#[derive(Debug, Deserialize)]
pub struct TradingParameters {
    pub max_positions: usize,
    pub risk_tolerance: f64,
    // Add other parameters as needed
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="configmanager-singleton"><a class="header" href="#configmanager-singleton">ConfigManager Singleton</a></h3>
<p><code>OnceCell</code> ensures that the <code>ConfigManager</code> is initialized only once in a thread-safe manner. <code>instance</code> method provides global access to the singleton instance. The <code>new</code> method is private to prevent direct instantiation.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use once_cell::sync::OnceCell;
use std::fs;

pub struct ConfigManager {
    config: Config,
}

impl ConfigManager {
    fn new() -&gt; Self {
        let config_data = fs::read_to_string(&quot;config.json&quot;)
            .expect(&quot;Failed to read configuration file&quot;);
        let config: Config = serde_json::from_str(&amp;config_data)
            .expect(&quot;Failed to parse configuration file&quot;);
        ConfigManager { config }
    }

    pub fn instance() -&gt; &amp;'static ConfigManager {
        static INSTANCE: OnceCell&lt;ConfigManager&gt; = OnceCell::new();
        INSTANCE.get_or_init(|| ConfigManager::new())
    }
    pub fn get_config(&amp;self) -&gt; &amp;Config {
        &amp;self.config
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="use-configmanager"><a class="header" href="#use-configmanager">Use ConfigManager</a></h3>
<p>Now we can’t just use this TWAP that depends on a ConfigManager in some other context, without carrying over the ConfigManager to the other context, e.g. Unit Tests.</p>
<pre><pre class="playground"><code class="language-rust">pub trait OrderExecution {
    fn execute(&amp;self);
}
pub struct TWAP;

impl OrderExecution for TWAP {
    fn execute(&amp;self) {
        let config_manager = ConfigManager::instance();
        let max_positions = config_manager.get_config().trading_parameters.max_positions;
        let risk_tolerance = config_manager.get_config().trading_parameters.risk_tolerance;
        // Implement execution logic using the configurations
    }
}
fn main() {
    let strategy = TWAP;
    strategy.execute();

    // Access the ConfigManager directly elsewhere
    let api_key = ConfigManager::instance().get_config().api_key.clone();
    println!(&quot;Using API Key: {}&quot;, api_key);
}
</code></pre></pre>
<p>In this example, we can't change the <code>ConfigManager</code> instance. We've basically set up an immutable singleton (or a single Flyweight object).</p>
<p>To implement a mutable singleton <code>ConfigManager</code> struct using <code>OnceCell</code>, you need to wrap the ConfigManager in an Interior Mutability Type like using <code>RefCell&lt;ConfigManager&gt;</code> for single-threaded applications or using using <code>Mutex&lt;ConfigManager&gt;</code> or <code>RwLock&lt;ConfigManager&gt;</code> for multi-threaded applications. For example:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>static CONFIG: OnceCell&lt;RefCell&lt;ConfigManager&gt;&gt; = OnceCell::new();
//Multi-threaded
static CONFIG: OnceCell&lt;Mutex&lt;ConfigManager&gt;&gt; = OnceCell::new();
<span class="boring">}
</span></code></pre></pre>
<h1 id="conclusion"><a class="header" href="#conclusion"><strong>Conclusion</strong></a></h1>
<p>Design patterns like Strategy, Decorator, Observer, and Factory Method provide proven and adaptable solutions that help developers create strong and efficient trading systems. By learning and using these patterns, developers can greatly improve the quality, maintainability, and performance of algorithmic trading systems. By abstracting the creation of objects, by encapsulating execution and trading strategies separately, we can build systems that are easier to maintain, extend, and adapt to changing market conditions.</p>
<h1 id="references"><a class="header" href="#references">References</a></h1>
<p>https://refactoring.guru/design-patterns/strategy</p>
<p>https://rust-unofficial.github.io/patterns/patterns/index.html</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../empty.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../empty.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
